package nyist.media.controller;

import nyist.media.bean.auth.MenuTreeBean;
import nyist.media.entity.admin.MenuAuth;
import nyist.media.service.MenuAuthService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author dcf
 * @date 2018/12/23
 */
@Controller
@RequestMapping("/admin/index")
public class IndexController {

    @Autowired
    private MenuAuthService menuAuthService;

    private void filterMenu(List<MenuTreeBean> list, Subject su){
        for(Iterator<MenuTreeBean> it=list.iterator();it.hasNext();) {
            MenuTreeBean menu = it.next();
            if(StringUtils.isNotEmpty(menu.getAuthorities())) {
                if(Stream.of(menu.getAuthorityArr()).noneMatch(a -> StringUtils.isEmpty(a) || su.isPermitted(a))){
                    it.remove();
                    continue;
                }
            }else if(StringUtils.isNotEmpty(menu.getAuthority())){
                if(!su.isPermitted(menu.getAuthority())) {
                    it.remove();
                    continue;
                }
            }
            filterMenu(menu.getChildren(), su);
        }
    }

    /**
     * 主页
     */
    @RequestMapping(method = RequestMethod.GET)
    public String index(ModelMap model) {
        List<MenuTreeBean> menus = menuAuthService.menuList();
        filterMenu(menus, SecurityUtils.getSubject());
        model.addAttribute("menuList", menus);
        model.addAttribute("principal", SecurityUtils.getSubject().getPrincipal());
        return "/index";
    }

    /**
     * 主页
     */
    @RequestMapping(value = "/board", method = RequestMethod.GET)
    public String main(ModelMap model) {
        return "/common/board";
    }
}
